if( hq == undefined ) {
        var hq = {};
}

hq.spacePolygon = {

	layers : {},


	overStyle : {color: "#aaaaff", weight: 1, opacity: .5},
	hiddenStyle : {color: "#aaaaff", weight: 1, opacity: 0},
	selectedStyle : {color: "#3f3fb5", weight: 1, opacity: .5},
	pendingStyle : {color: "#FF0000", weight: 1, opacity: 1},
	pendingColor : '#FF0000',
	
	weight : 1,

	layerType : 'neighborhoods',

	BaseUrl : $j('#hqDomain').val(),

	UserRole : $j('#userRole').val(),

	CensusLevel: 14,

	init : function() {
		console.group('spacePolygon::init');

		// Load the block colors
                this.colors = {};
                this.getMeta();

		// ALL polygons that are loaded, regardless of where and if they are visible
 		this.polys = {};
                this.zoom = hq.map.gMap.getZoom();
                this.zoomName = '';
//		this.loadedSpaces = {};
		this.loaded = [];
		this.activeLayer = $j('a.activeLayer').attr('layerId');


		// Pray this executes after the first postPaneLoad is triggere
		var sp = this;
		jQuery.each(jQuery.browser, function(i, val) {
                        if(val) {
                                sp.browser = i;
                        }
                });

		this.initLoadedSpaces();
			
		this.getSpacePoints();

		GEvent.addListener( hq.map.gMap, 'moveend', toolbox.delegate( this.getSpacePoints, this ) );
		GEvent.addListener( hq.map.gMap, 'mouseout', toolbox.delegate( this.onMapMouseOut, this ) );
		GEvent.addListener( hq.map.gMap, 'singlerightclick', toolbox.delegate(this.onRightClick, this) );


		// Intercept clicks on the left sidebar to spaces

		$j( '#contentWrapper' )
		//	.bind( 'polygonsCreated', toolbox.delegate(this.onPostPaneLoad, this))
			.bind( 'layerChange', toolbox.delegate(this.clearLoaded, this))
			.bind( 'paneLoaded', toolbox.delegate(this.onPaneLoad, this));	
		
		$j('#applyEditsLink').click(toolbox.delegate(this.applyAllEdits, this));
		$j('#rejectEditsLink').click(toolbox.delegate(this.rejectAllEdits, this));
		$j('#recreateNHBtn').click(toolbox.delegate(this.recreateNhs, this));	
		$j('#displayLayers').click(toolbox.delegate(this.toggleDisplay, this));
		$j('#clearSelectedLink').click(toolbox.delegate(this.clearSelected, this));

		$j('#contentWrapper').trigger('paneLoaded');
	
		// Add the pending color key
		$j('#pendingColor').css('background-color', this.pendingColor);
	
		console.groupEnd();
	},	

	// Hide the polygons or redraw them
        toggleDisplay: function(evt) {
		var checked = $j('#displayLayers:checked').val();
	
		if(!checked) { 
		for(var i in this.polys) {
                        for(var j in this.polys[i]) {

                                if(this.polys[i] && this.polys[i][j]) {
//                                        this.polys[i][j].setFillStyle(this.hiddenStyle);
                                        this.polys[i][j].hide();
                                }

                        }
                }
		} else {
			this.getSpacePoints();
		}

		return true;
	},

	applyAllEdits: function() {
                $j.ajax({
                        url: '/ajax/crt.proc.php',
                        data : {
                                op: 'applyAllEdits'
                        },
                        dataType : 'json',
                        success: function(res) {
				var zoom = hq.map.gMap.getZoom();
	                        var center = hq.map.gMap.getCenter();
        	                $j('#zoom').val(zoom);
                	        $j('#center').val(center);
				window.location.reload(true);
			}
                });

	},

    rejectAllEdits: function() {
                $j.ajax({
                        url: '/ajax/crt.proc.php',
                        data : {
                                op: 'rejectAllEdits'
                        },
                        dataType : 'json',
                        success: function(res) {
                                var zoom = hq.map.gMap.getZoom();
                                var center = hq.map.gMap.getCenter();
                                $j('#zoom').val(zoom);
                                $j('#center').val(center);
                                window.location.reload(true);
                        }
                });

        },

	recreateNhs: function() {
		$j('#nhSpinner').show();
		$j.ajax({
			url: '/ajax/recreate-nhs.php',
			dataType: 'json',
			success: toolbox.delegate(this.recreateNhsCB, this)
		});
	},

	recreateNhsCB: function() {
		$j('#nhSpinner').hide();
		$j('#recreateNhMsg').show();
		hq.labels.getLabels();
	},

	getMeta : function() {
		$j.ajax({
			dataType: 'json',
			url: "/ajax/get-poly-meta.php",
			success: toolbox.delegate(this.getMetaCB, this),
			error: function(res) {
			}
		});
	},

	getMetaCB : function(res) {
		for(var i in res) {
			this.colors[i] = res[i];
		}
	},


	//TODO - Modify this function to assign color to all selected polys
	onPaneLoad : function() {

		// Find loaded options, delete them if polygon doesn't exist
		var selected = $j('#loadedBlocks').find('option:selected');
		for(var i=0; i<selected.length; i++)	{	
			var val = $j(selected[i]).val();
			if(!this.polys[this.zoomName][val])
					selected.remove();		
		}

		// Submit has been clicked, do the update
		var sp = this;
		$j('#nhSubmit').click(
			
		function(evt) {
			var selected = $j('#loadedBlocks').find('option:selected');
			var ids = [];
			// get the color associated with the selected block, assign that color to all loaded	
			var name = $j('#nhSelect').find('option:selected').val();
			var color = sp.colors[name];
			
			var $tgt = $j(evt.target);

			// Recreate nhs for editor changes
                        if(sp.UserRole==2) {
				$j( '#loadingMsg' ).fadeIn( 2000 )

                                $j.ajax({
                                        url: '/ajax/recreate-nhs.php',
                                        data : {
                                                neighborhoods: name
                                        },
					success: function(res) {
						$j( '#loadingMsg' ).fadeOut( 2000 )
						var form = $tgt.parents('form:first');
						form.trigger('submit');
					}

                                });
                        }

			for(var i=0; i<sp.loaded.length; i++) {
				if(sp.UserRole==1) {
					sp.loaded[i].setFillStyle(sp.pendingStyle);
				} else {
					sp.loaded[i].setFillStyle( {color: '#' + color, weight: sp.weight, opacity: .5} );
				}

				
				sp.loaded[i].hqData['color'] = sp.UserRole==1 ? sp.pendingColor : color;
				sp.polys[sp.zoomName][sp.loaded[i].hqData['hqId']].hqData['color'] = sp.UserRole==1 ? sp.pendingColor : color;
				ids.push(sp.loaded[i].hqData['hqId']);
			}


			var zoom = hq.map.gMap.getZoom();
			var center = hq.map.gMap.getCenter();
			$j('#zoom').val(zoom);
			$j('#center').val(center);
	
			// Reload immediately for non editors
			// Editors have to wait for the ajax call above to complete	
			var ret = sp.UserRole==2 ? false : true;	
			return ret;
		});

		// Clear loaded on button click
                $j('#clearLoaded').click(function(evt) {
			var zoom = hq.map.gMap.getZoom();
                        var center = hq.map.gMap.getCenter();

                        $j('#zoom').val(zoom);
                        $j('#center').val(center);

			sp.clearBlocks(evt);
			return true;
		});

	},

	getSpacePoints : function() {
		console.group('spacePolygon::getSpacePoints');
		//$j('a.spaceItem').click(toolbox.delegate(this.onSpaceBoxClick, this));
		if( this.curTrans ) {
                        console.info('Previous space search in progress, aborting');
                        this.curTrans.abort();
                        this.curTrans = null;
                }
		
		var loadedSpaces = false;

                this.zoom = hq.map.gMap.getZoom();
		this.activeLayer = this.zoom < this.CensusLevel ? false : 'census';

		var displayLayers = $j('#displayLayers:checked').val();	

		if(!this.activeLayer || !displayLayers) {
			for(var i in this.polys) {
				for(var j in this.polys[i]) {
					this.polys[i][j].hide();
				}
			}
			console.groupEnd();
			return false;
		}
	
                if(!displayLayers || displayLayers==undefined) {
			console.groupEnd();
			return false;
		}

				
			
		if(!this.loadedSpaces[this.activeLayer]) this.loadedSpaces[this.activeLayer] = {}; 

		var extents = toolbox.getExtents(hq.map.gMap);

		$j( '#loadingMsg' ).fadeIn( 2000 );

		this.curTrans = $j.ajax({
                        url : '/ajax/get-space-points.php',
                        data : {
                                metroId : $j('#metroId').val(),
				zoom : this.zoom,
				minX : extents.minX,
				maxX : extents.maxX,
				minY : extents.minY,
				maxY : extents.maxY,
				layer : this.activeLayer,
				ajax: 1
                        },
			dataType: "json",
                        success : toolbox.delegate( this.getSpacePolygon, this, this.activeLayer  )
			

                });
		
		console.groupEnd();

		return false;
	},

        getSpacePolygon : function(res, resStatus, activeLayerId) {
		console.group('spacePolygon::getSpacePolygon');
		var i = 0;
		var oldZoom = this.zoomName;
		this.zoomName = activeLayerId;
		var layer = poly = null;
		for(var j in this.polys) {
			if(j==this.activeLayer)
	                        continue;

			layer = this.polys[j]; //this.layers[j];
			for(i in layer) {
				poly = this.polys[j][i];


				if(!poly.isHidden() &&  !poly.loaded) {
				}
			}
		}
		
		for(i in res) {
			if(!this.polys[this.zoomName])	this.polys[this.zoomName] = {};
			if(!this.polys[this.zoomName][i]) {
				this.polys[this.zoomName][i] = this.createPolygon(res[i], i);
			
			}
			this.polys[this.zoomName][i].show();
		}

		$j('#contentWrapper').trigger('polygonsCreated');

		$j( '#loadingMsg' ).fadeOut( 2000 );

		console.groupEnd();
		
        },

	// Create and return a polygon
	createPolygon : function(ptData, i) {
		var color = '';
		var opacity = '';
		if(ptData['name'] || ptData['pending']) {
			color = ptData['pending'] ? this.pendingColor : '#' + this.colors[ptData['name']];
			opacity = ptData['pending'] ? .8 : .5
		} else {
			color = '#FFFFFF';
			opacity = 0;
		}
	
		var polygon = GPolygon.fromEncoded({
                polylines: [
                        {
                          color: '#000000',
                          weight: this.weight,
                          opacity: .5,
                          points: ptData['points'][0],
                          levels: ptData['points'][1],
                          zoomFactor: 16,
                          numLevels: 1,
			  opts : {mouseOutTolerance: 1}
                        }

                        ]
                        ,
                        outline: true,
                        color: color,
                        opacity: opacity,
                        fill: true,
			opts : {mouseOutTolerance: 1}

                
	        });

	
		// Save layerId and hqId in the polygon
		polygon.hqData = {
			layerId : this.activeLayer,
			hqId : i,
			name: ptData['name'],
			color: color,
			opacity: opacity
		};
	
		hq.map.gMap.addOverlay(polygon);
		GEvent.addListener( polygon, 'mouseout', toolbox.delegate(this.onMouseOut, this, i, polygon ) );
                GEvent.addListener( polygon, 'mouseover', toolbox.delegate(this.onMouseOver, this, i, polygon ) );

		if(this.UserRole==1 || this.UserRole==2)
			GEvent.addListener( polygon, 'click', toolbox.delegate(this.onClick, this, i , polygon) );

		GEvent.addListener( polygon, 'singlerightclick', toolbox.delegate(this.onRightClick, this, i , polygon) );

		$j('#clear_'+i).click(toolbox.delegate(this.onClick, this, i , polygon) );

		return polygon;

	},


	// DO ajax call here to get all pending edits, show them in info win
	onRightClick : function(point, src, polygon) {
		console.group('spacePolygon::onRightClick');

		//hq.loadingMsg.show();
		$j.ajax({
			url: '/ajax/crt.proc.php',
			data : {
				op: 'getPending',
				id: polygon.hqData['hqId']
			},
			dataType : 'json',
			success: toolbox.delegate(this.onRightClickCB, this, point, polygon)
		});


		console.groupEnd();
	},

	// Display info window with pending changes listed if they exist
	onRightClickCB : function(res, success, point, polygon) {
		console.group('spacePolygon::onRightClickCB');

		//hq.loadingMsg.hide();

		var html = []; 
		var latlng = hq.map.gMap.fromContainerPixelToLatLng(point);
		var len = res.length;

		html[html.length] = "<div class='crtMapWin'>";
		html[html.length] = "Block&nbsp;#" + polygon.hqData['hqId'] + "\n&nbsp;-&nbsp;"
		html[html.length] = polygon.hqData['name'] ? polygon.hqData['name'] + "&nbsp;&nbsp;<a href='javascript:void(0);' onclick=\"hq.spacePolygon.addToExports('" + polygon.hqData['name'] + "', " + polygon.hqData['hqId'] + "); \" id='addExport'>add&nbsp;to&nbsp;exports</a>" : 'Not named';

		if(len > 0) {

			html[html.length] = "<br /><br />";
			html[html.length] = "<strong>Pending changes:</strong>";
			html[html.length] = "<table>";

			for(var i=0; i < len; i++) {
				html[html.length] = "<tr><td>Name:&nbsp;" + res[i].name + "</td><td>User:&nbsp;" + res[i].username + "</td>";
				if(this.UserRole==2) { 
					html[html.length] = "<td><a onclick='hq.spacePolygon.applyClick(" + polygon.hqData['hqId']+ "," + res[i].id + ");' class='applyLink' href='#' id='apply_" + res[i].id + "'>Apply</a></td>";
                        		html[html.length] = "&nbsp;<a href='javascript: void(0);' onclick='hq.spacePolygon.rejectEdit(" + res[i].id + ", " + polygon.hqData['hqId'] + ", \"" + polygon.hqData['name'] + "\");'>Reject</a>&nbsp;";

				} 
				
				html[html.length] = "</tr>";
			}

			html[html.length] = "</table>";
		}

		html[html.length] = "</div>";

                hq.map.gMap.openInfoWindowHtml(latlng, html.join(''), {suppressMapPan: true, maxWidth: 300});


		console.groupEnd();
	},

	rejectEdit: function(id, hqId, name) {
		var sp = this;

		$j.ajax({
                        url: '/ajax/crt.proc.php',
                        data : {
                                op: 'rejectEdit',
                                id: id,
				hqId: hqId
                        },
                        dataType : 'json',
                        success: function(res) {
				if(res.length) {
					hq.map.gMap.closeInfoWindow();
				} else {
					var color = name ? sp.colors[name] : false;
					if(color) {
						sp.polys[sp.activeLayer][hqId].setFillStyle({color:  '#' + color , weight: sp.weight, opacity: .5} );
						sp.polys[sp.activeLayer][hqId].hqData['color'] = '#' + color;
						
					} 
					else {
						sp.polys[sp.activeLayer][hqId].setFillStyle(sp.hiddenStyle);
						sp.polys[sp.activeLayer][hqId].hqData['color'] = '';
						sp.polys[sp.activeLayer][hqId].hqData['opacity'] = 0;
					}

					hq.map.gMap.closeInfoWindow();
				}
			}
                });

	},

	addToExports : function(name) {
		var html = [];
		var opt = $j('#exportNhs').find('option[value="' + name + '"]').get();
		var append = (opt && opt.length) ? false : true;

		if(append) {
			html[html.length] = "<option value='" + name + "'>" + name + "</option>";
			$j('#exportNhs').append(html.join(''));
		}
	},

	applyClick : function(hqId, nhId) {
		var sp = this;

		$j.ajax({
			url: '/ajax/crt.proc.php',
			data : {
				op: 'applyChanges',
				hqId: hqId,
				nhId: nhId
			},
			dataType: 'json',
			success: function(res) {
				if(res) {	
					var color = sp.colors[res];
					sp.polys[sp.activeLayer][hqId].setFillStyle({color:  '#' + color , weight: sp.weight, opacity: .5} );
					sp.polys[sp.activeLayer][hqId].hqData['color'] = '#' + color;
					hq.map.gMap.closeInfoWindow();
				}
			}
		});
	},

	onOverlayChange : function(evt, i) {
		console.group('spacePolygon::onOverlayChange');

		var $tgt = $j(evt.target);
		this.activeLayer = $tgt.attr('layerId');

		console.groupEnd();
	},

	onMouseOver : function(evt, i, polygon) {
		var zoom = hq.map.gMap.getZoom();

		if(this.loaded) {
			for(var j=0; j<this.loaded.length; j++) {
                        	if(this.loaded[j].hqData['hqId'] ==i) 
					return false;
                        }
                }

	
		var curSpace = this.loadedSpaces[this.activeLayer];
		if(curSpace) {
		var len = curSpace.length;
	 	for(var j=0; j<len; j++) {
        	                if(curSpace[j]==i) {
					console.info('returning...');
                        //	        return;
				}
        	}
		}
		if(this.polys[this.activeLayer][i]) {
			this.polys[this.activeLayer][i].setFillStyle(this.overStyle);
		} else {
		}

	},

	onMouseOut : function(evt, i, polygon) {
		if(!this.activeLayer) {
			console.info('Returning...');
			return;
		}

		// Don't switch loaded polygon
                if(this.loaded) {
                        for(var j=0; j<this.loaded.length; j++) {
                                if(this.loaded[j].hqData['hqId'] ==i)
                                        return false;
                        }
                }

//		for(var j=0; j<len; j++) {
  //      	               if(curSpace[j]==i)
    //                            return;
//	        }

		var opacity = polygon.hqData['opacity'];
		if(this.polys[this.activeLayer][i].hqData['color']) {
			var fill =  {color: this.polys[this.activeLayer][i].hqData['color'], weight: this.weight, opacity: opacity};
			polygon.setFillStyle(fill);

		}
		
	},

	onClick : function(evt, i, polygon) {
		console.group('spacePolygon::onClick');
		var zoom = hq.map.gMap.getZoom();

		var $target = $j( evt.target );
		var data = polygon.hqData;
		var found = false;
		
		for(var j=0; j<this.loaded.length; j++) {
			if(this.loaded[j].hqData['hqId'] ==i) {
				found = true;
				this.loaded.splice(j, 1);
				break;
			}
		}
		
		var op = '';
		if(found) {
			op = 'removeBlock';
			polygon.setFillStyle( {color:  polygon.hqData['color'] , weight: this.weight, opacity: .5} );
			$j('option[value="' + polygon.hqData['hqId'] + '"]').remove();		
		} else {
			op = 'addBlock';
			polygon.setFillStyle( this.selectedStyle );
			this.loaded.push(polygon);

			var name = polygon.hqData['name'] ? polygon.hqData['name'] : 'Not named';
	                $j('<option value="' + polygon.hqData['hqId'] + '" selected>Block #'+polygon.hqData['hqId'] + ' - ' + name + '</option>').appendTo('select[name="loadedBlocks[]"]');		
		}

		var bounds = hq.map.getBounds();


//	$j( '#loadingMsg' ).fadeIn( 1000 );
		$j.ajax({
			url: "/",
			data :{
				op: op,
				id: i,
				ajax: 1,
                                minX: bounds.minX,
                                maxX: bounds.maxX,
                                minY: bounds.minY,
                                maxY: bounds.maxY

			},
		//	success: toolbox.delegate(this.onClickCB, this),
			error: toolbox.delegate(this.error, this)
		});	
		
		$j('.removeBlock').unbind('click').click(function(evt) {
			$tgt = $j(evt.target);
			var id = parseInt($tgt.attr('id'));
			var test = $tgt.parents('option:first');
			var test2 = test;
				
		});
		console.groupEnd();
	
		return false;

	},

	// Clear the multi select
	clearSelected: function(evt) {
		$j('select[name="loadedBlocks[]"]').find('option').remove();
		for(var i=0; i < this.loaded.length; i++) {
			this.loaded[i].setFillStyle( {color:  this.loaded[i].hqData['color'] , weight: this.weight, opacity: .5} );
                        $j('option[value="' + this.loaded[i].hqData['hqId'] + '"]').remove();
		}

		this.loaded = [];
		
	},

	clearBlocks : function(evt) {
		console.group('spacePolygon::clearBlocks');

                for(var i=0; i<this.loaded.length; i++) {
                	this.loaded[i].setFillStyle( {color:  this.loaded[i].hqData['color'], weight: this.weight, opacity: .5} );
		}
	
		$j('#loadedBlocks').html('<option>&nbsp;</option>');	

		this.loaded = [];
		
		var bounds = hq.map.getBounds();
		$j( '#loadingMsg' ).fadeIn( 1000 );	
                $j.ajax({
                        url: "/",
                        data :{
                                clearLoaded: true,
                                ajax: 1,
				minX: bounds.minX,
				maxX: bounds.maxX,
				minY: bounds.minY,
				maxY: bounds.maxY
                        },
			success: function() { $j('#loadingMsg').fadeOut(1000); }
                });

		console.groupEnd();
		return false;
	},

	onClickCB : function(res) {
		var startStr = '<!-- BEGIN_CONTENT_WRAPPER -->';
		var endStr = '<!-- END_CONTENT_WRAPPER -->';
		var start = res.indexOf(startStr);
		var end = res.indexOf(endStr);

		if(start>=0 && end>=0) {
			end += endStr.length + 1;
			var length = end - start;
			var content = res.substr(start, length);

			$j('#contentWrapper').html(content);
			$j('#contentWrapper').trigger('paneLoaded');	
		}

		$j( '#loadingMsg' ).fadeOut( 1000 );
	},

	onMapMouseOut : function(evt) {
             for(var i in this.polys) {
			if(this.polys[i]) {
	                        for(var j in this.polys[i]) {
					if(this.polys[i][j]) {
						GEvent.trigger(this.polys[i][j], 'mouseout', i);
					}
	                        } 
			}
             }
		
	},

	// Initialize spaces based on links in the class 'overlay'
	// The key in each loaded space is its layer id
	initLoadedSpaces : function() {
		var sp = this;

		this.loadedSpaces = {};
	
		$j('a.overlay').each(function() {
			sp.loadedSpaces[$j(this).attr('layerId')] = [];
		});
	},

	error: function(res) {
	}


};

$j( document ).ready( toolbox.delegate( hq.spacePolygon.init, hq.spacePolygon ) );
